package com.jumper.property.comparer.core.spi;

import com.jumper.property.comparer.core.annotations.SPI;

import java.util.*;

/**
 * SPI加载器
 */
public class SPILoader {

    /**
     * 缓存
     */
    private final static Map<Class<?>, Object> SPI_CACHE = new HashMap<>();

    public static <T> T load(Class<T> spiCls) {
        return load(spiCls, false);
    }

    public static <T> T load(Class<T> spiCls, boolean forceLoad) {
        if (SPI_CACHE.containsKey(spiCls)) {
            if (forceLoad) {
                SPI_CACHE.remove(spiCls);
            } else {
                return (T) SPI_CACHE.get(spiCls);
            }

        }
        ServiceLoader<T> loader = ServiceLoader.load(spiCls);
        List<Node<T>> nodes = new ArrayList<>();
        loader.forEach(instance -> nodes.add(new Node<T>(instance)));
        nodes.sort(Node::compareTo);
        if (nodes.isEmpty()) {
            return null;
        } else {
            T val = nodes.get(0).val;
            SPI_CACHE.put(spiCls, val);
            return val;
        }
    }

    /**
     * 可排序SPI节点
     */
    private static class Node<T> implements Comparable<Node<T>> {
        private final T val;
        private final int sort;

        public Node(T val) {
            this.val = val;
            this.sort = getSort(val);
        }

        private int getSort(T val) {
            SPI spi = val.getClass().getAnnotation(SPI.class);
            return spi == null ? 0 : spi.value();
        }

        @Override
        public int compareTo(Node<T> o) {
            return Integer.compare(this.sort, o.sort);
        }
    }
}
